
package com.cyys.common.ql;

import com.cyys.common.constant.CommonConstants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;


/**
 * $.ajax后需要接受的JSON
 * 
 * @author
 * 
 */
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public class AR<T> implements Serializable {

	@Getter
	@Setter
	@ApiModelProperty(value = "返回标记：成功标记=0，失败标记=-1")
	private int code = -1;//代码

	@Getter
	@Setter
	@ApiModelProperty(value = "返回信息")
	private String msg = "操作成功";// 提示信息

	@Getter
	@Setter
	@ApiModelProperty(value = "数据")
	private T data;

	@JsonIgnore//返回对象时忽略此属性
	public String getJsonStr() {   //返回json字符串数组，将访问msg和key的方式统一化，都使用data.key的方式直接访问。
		String json = JsonMapper.getInstance().toJson(this);
		return json;
	}

	public static <T> AR<T> ok() {
		return restResult(null, CommonConstants.SUCCESS, null);
	}

	public static <T> AR<T> ok(String msg) {
		return restResult(null, CommonConstants.SUCCESS, msg);
	}

	public static <T> AR<T> ok(T data) {
		return restResult(data, CommonConstants.SUCCESS, null);
	}

	public static <T> AR<T> ok(T data, String msg) {
		return restResult(data, CommonConstants.SUCCESS, msg);
	}

	public static <T> AR<T> failed() {
		return restResult(null, CommonConstants.FAIL, null);
	}

	public static <T> AR<T> failed(String msg) {
		return restResult(null, CommonConstants.FAIL, msg);
	}

	public static <T> AR<T> failed(int code, String msg) {
		return restResult(null, code, msg);
	}

	public static <T> AR<T> failed(T data) {
		return restResult(data, CommonConstants.FAIL, null);
	}

	public static <T> AR<T> failed(T data, String msg) {
		return restResult(data, CommonConstants.FAIL, msg);
	}

	private static <T> AR<T> restResult(T data, int code, String msg) {
		AR<T> apiResult = new AR<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

}
